package com.gjl.app.oauth;

import com.gjl.app.oauth.common.Encoder;
import com.gjl.app.oauth.common.OauthUtil;
import com.gjl.app.oauth.endpoint.Consumer;
import com.gjl.app.oauth.endpoint.ServiceProvider;

public class OauthHandler {

//	Not used currently, only get method is supported in this version
//	private static final String POST_METHOD = "POST";
	
	private static final String GET_METHOD = "GET";
	
	private static final String AMP = "&";
	
	private Consumer consumer;
	
	private ServiceProvider provider;
	
	public OauthHandler(Consumer consumer, ServiceProvider provider) {
		this.consumer = consumer;
		this.provider = provider;
	}
	
	private String composeBaseString() {
		StringBuffer baseBuffer = new StringBuffer(GET_METHOD).append(AMP);
		baseBuffer.append(OauthUtil.urlEncode(provider.getUnauthorizedUrl())).append(AMP);
		baseBuffer.append(consumer.getOauthParam());
		return baseBuffer.toString();
	}
	
	public String getSignature() {
		String base = composeBaseString();
		//Please be aware that the key MUST be urlencoded here, or a invalid signature will be returned
		String key = OauthUtil.urlEncode(consumer.getConsumerSecret());
		key += AMP;
		return OauthUtil.urlEncode(OauthUtil.hmac(base, key));
	}
	
	public static void main(String[] args) {
		ServiceProvider provider = ServiceProvider.getGoogleServiceProvider();
		Consumer consumer = new Consumer("maleoapp.appspot.com", "FvtA7CPFv7U4rkWk/KkJX1zI", "http://maleoapp.appspot.com");
		OauthHandler handler = new OauthHandler(consumer, provider);
		System.out.println(handler.composeBaseString());
		System.out.println(handler.getSignature());
	}
}
